package app

import (
	"encoding/json"
	"github.com/pkg/errors"
	"io"
	"sync"
	"time"
)

const (
	rtcpPLIInterval = time.Second * 3
)

type Client struct {
	ClientId string `json:"client_id"`
	PeerConn  *sync.Map
	RemotePeer *Connection;
	WsConn io.ReadWriteCloser
}


type wsClientMsg struct {
	Cmd      string `json:"cmd"`
	RoomID   string `json:"roomid"`
	ClientID string `json:"clientid"`
	Sdp      string `json:"sdp"`
	Msg      map[string]interface{} `json:"msg"`
}

// wsServerMsg is a message sent to a client on behalf of another client.
type wsServerMsg struct {
	Msg   string `json:"msg"`
	Error string `json:"error"`
}

func NewClient(ClientId string) *Client {
	return &Client{
		PeerConn:&sync.Map{},
		ClientId:ClientId,
	};
}

func (client *Client) CreatePeer(sdp string) string {
	conn := NewConnection();
	clientSdp := conn.PushPeer(sdp);
	client.RemotePeer = conn;
	return clientSdp;
}

func (client *Client) LinkPeer(otherClient *Client) error {
	if _,ok := client.PeerConn.Load(otherClient.ClientId);ok == true {
		return  errors.New("clientid confied");
	}

	client.RemotePeer.PullPeer();
	client.PeerConn.Store(otherClient.ClientId ,otherClient.RemotePeer)

	return nil;
}

func (client *Client) RemovePeer(otherClient *Client) error{
	if _,ok := client.PeerConn.Load(otherClient.ClientId);ok != true {
		return  errors.New("clientid confied");
	}

	client.PeerConn.Delete(otherClient.ClientId)
	return nil;
}

func sendServerErr(w io.Writer, errMsg string) error {
	m := wsServerMsg{
		Error: errMsg,
	}
	return send(w, m)
}

// send writes a generic object as JSON to the writer.
func send(w io.Writer, data interface{}) error {
	enc := json.NewEncoder(w)
	if err := enc.Encode(data); err != nil {
		return err
	}
	return nil
}
